package com.gxa.hualianeshop.component;

import com.gxa.hualianeshop.config.RabbitConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息的处理方法, 添加过期时间
     * @return
     */
    private MessagePostProcessor messagePostProcessor() {
        return new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置有效期30分钟(单位毫秒)
                //message.getMessageProperties().setExpiration("1800000");
                //测试10秒后过期
                message.getMessageProperties().setExpiration("10000");
                return message;
            }
        };
    }

    public void send(Object message){
        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_EXCHANGE,
                RabbitConfig.ORDER_ROUTING_KEY,message,messagePostProcessor());
    }
}
